<template>
    <view v-show="isVisible" class="TextEditor">
        <view class="editor-container" :class="{ active: isActive }">
            <view class="editor-header">
                <textarea v-model="textContent" cursor-spacing="60" placeholder="请输入内容" @input="handleInput"></textarea>
                <view class="header-button" @click="confirmChanges">确定</view>
            </view>

            <view class="action-buttons">
                <view class="action-button" @click="copyText">
                    <image src="/static/icon/copy.svg" class="icon" />
                    <text class="label">复制</text>
                </view>

                <view class="action-button" @click="deleteText">
                    <image src="/static/icon/del.svg" class="icon" />
                    <text class="label">删除</text>
                </view>

                <view class="action-button" @click="showFontColorPicker">
                    <image src="/static/icon/font_color.svg" class="icon" />
                    <text class="label">文字颜色</text>
                </view>

                <view class="action-button" @click="showFontFamilySelector">
                    <image src="/static/icon/fontFamliy.svg" class="icon" />
                    <text class="label">字体</text>
                </view>

                <view class="action-button" @click="showStrokeWidthController">
                    <image src="/static/icon/stroke.svg" class="icon" />
                    <text class="label">描边</text>
                </view>

                <view class="action-button" @click="showStrokeColorPicker">
                    <image src="/static/icon/strokeColor.svg" class="icon" />
                    <text class="label">描边颜色</text>
                </view>

                <view class="action-button" @click="showCharSpacingController">
                    <image src="/static/icon/font_space.svg" class="icon" />
                    <text class="label">间距</text>
                </view>

                <view class="action-button" @click="showLineHeightController">
                    <image src="/static/icon/line_height.svg" class="icon" />
                    <text class="label">行高</text>
                </view>

                <view class="action-button" @click="showBendDegreeController">
                    <image src="/static/icon/bend.svg" class="icon" />
                    <text class="label">弯曲</text>
                </view>

                <view class="action-button" @click="alignLeft">
                    <image src="/static/icon/leftAilgn.svg" class="icon" />
                    <text class="label">左对齐</text>
                </view>

                <view class="action-button" @click="alignCenter">
                    <image src="/static/icon/centerAlign.svg" class="icon" />
                    <text class="label">中对齐</text>
                </view>

                <view class="action-button" @click="alignRight">
                    <image src="/static/icon/rightAlign.svg" class="icon" />
                    <text class="label">右对齐</text>
                </view>
            </view>

            <!-- 描边控制器 -->
            <view :class="{ 'stroke-controller': true, 'visible': isStrokeControllerVisible }">
                <text class="label">描边</text>
                <slider class="slider" min="0" step="0.01" max="5" :value="strokeWidth" activeColor="#FF5E10"
                        @changing="handleStrokeWidthChanging" @change="handleStrokeWidthChange" />
                <image class="close-icon" @click="hideStrokeController" src="/static/icon/icon-close.svg" />
            </view>

            <!-- 间距控制器 -->
            <view :class="{ 'char-spacing-controller': true, 'visible': isCharSpacingControllerVisible }">
                <text class="label">间距</text>
                <slider class="slider" min="0" step="1" max="1000" :value="charSpacing" activeColor="#FF5E10"
                        @changing="handleCharSpacingChanging" @change="handleCharSpacingChange" />
                <image class="close-icon" @click="hideCharSpacingController" src="/static/icon/icon-close.svg" />
            </view>

            <!-- 行高控制器 -->
            <view :class="{ 'line-height-controller': true, 'visible': isLineHeightControllerVisible }">
                <text class="label">行高</text>
                <slider class="slider" min="0" step="0.01" max="5" :value="lineHeight" activeColor="#FF5E10"
                        @changing="handleLineHeightChanging" @change="handleLineHeightChange" />
                <image class="close-icon" @click="hideLineHeightController" src="/static/icon/icon-close.svg" />
            </view>

            <!-- 弯曲控制器 -->
            <view :class="{ 'bend-degree-controller': true, 'visible': isBendDegreeControllerVisible }">
                <text class="label">弯曲</text>
                <slider class="slider" min="0" step="1" max="360" :value="bendDegree" activeColor="#FF5E10"
                        @changing="handleBendDegreeChanging" @change="handleBendDegreeChange" />
                <image class="close-icon" @click="hideBendDegreeController" src="/static/icon/icon-close.svg" />
                <text class="warning">多行文本不适用弯曲效果</text>
            </view>

            <!-- 字体列表 -->
            <view :class="{ 'font-family-selector': true, 'visible': isFontFamilySelectorVisible }">
                <view class="header">
                    <text class="label">选择字体</text>
                    <image class="close-icon" @click="hideFontFamilySelector" src="/static/icon/icon-close.svg" />
                </view>

                <view class="font-family-list">
                    <view :class="{ 'font-family-item': true, 'active': fontFamily === fontItem.id }" :key="i"
                          @click="changeFontFamily(fontItem.id)" v-for="(fontItem, i) in fontList">
                        <image :src="fontItem.img" class="font-preview" crossOrigin='anonymous' />
                        <image src="/static/icon/needLoad.svg" class="status-icon"
                               v-if="!loadingFonts.includes(fontItem.id) && !loadedFonts.includes(fontItem.id) && !loadErrorFonts.includes(fontItem.id)" />
                        <image src="/static/icon/loadding2.svg" class="status-icon"
                               v-if="loadingFonts.includes(fontItem.id) && !loadedFonts.includes(fontItem.id)" />
                        <image src="/static/icon/load_err.svg" class="status-icon"
                               v-if="!loadingFonts.includes(fontItem.id) && loadErrorFonts.includes(fontItem.id)" />
                        <image src="/static/ok.svg" class="status-icon" v-if="loadedFonts.includes(fontItem.id)" />
                    </view>
                </view>
            </view>
        </view>

        <!-- 色盘 -->
        <t-color-picker ref="colorPicker" :color="currentColor" :showOk="true" @confirm="handleColorConfirm" />
    </view>
</template>

<script>
import textEditorerStore from "./textEditorerStore";
import designerStore from "../../DesignEditor/designerStore";
import designEditorRender from "../../DesignEditor/designEditorRender";
import {
    toJS,
    autorun
} from "mobx";
import {
    Color
} from "../../myThree/build/three.module";
import fontManage from "../../myFabric/fontManage";
import cloneDeep from "lodash/cloneDeep";

export default {
    name: "TextEditor",
    props: {},
    data() {
        return {
            textContent: '',

            isVisible: false,
            isActive: false,
            isStrokeControllerVisible: false,
            strokeColor: "#000000", // 描边颜色
            strokeWidth: 0, // 描边

            isCharSpacingControllerVisible: false, // 显示间距控制器
            charSpacing: 0, // 间距

            isLineHeightControllerVisible: false, // 显示行高控制器
            lineHeight: 0, // 行高

            isBendDegreeControllerVisible: false, // 显示弯曲控制器
            bendDegree: 0, // 弯曲角度

            currentColor: {
                r: 255,
                g: 255,
                b: 255,
                a: 1
            }, // 颜色
            colorType: "font_color", // 颜色类型，font_color为文字颜色，stroke_color为描边颜色

            isFontFamilySelectorVisible: true, // 显示字体列表
            fontFamily: "", // 字体

            fontList: cloneDeep(fontManage.fontlist),

            loadingFonts: [], // 正在加载的字体
            loadedFonts: [], // 已加载的字体
            loadErrorFonts: [], //加载失败的字体

        };
    },
    created() { },
    mounted() {
        this.dispose = autorun(() => {
            const {
                show,
                active
            } = textEditorerStore;
            this.isVisible = show;
            this.isActive = active;
            if (show) {
                const activeObject = designEditorRender.getActiveObject();
                if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                    this.textContent = activeObject.get("text");
                }
            }
        });

        this.dispose1 = autorun(() => {
            const {
                activeObjectType
            } = designerStore;
            if (!activeObjectType) {
                textEditorerStore.close();
                this.isStrokeControllerVisible = false;
                this.isCharSpacingControllerVisible = false;
                this.isLineHeightControllerVisible = false;
                this.isBendDegreeControllerVisible = false;
                this.isFontFamilySelectorVisible = false;
            }
        })

        this.dispose2 = autorun(() => {
            this.loadingFonts = toJS(fontManage.store.loadingFonts);
            this.loadedFonts = toJS(fontManage.store.loadedFonts);
            this.loadErrorFonts = toJS(fontManage.store.loadErrFonts);
        })
    },
    destroyed() {
        this.dispose();
        this.dispose1();
        this.dispose2();
    },
    methods: {
        handleInput(e) {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                const {
                    value
                } = e.detail;
                activeObject.set("text", value);
                designEditorRender.requestRenderAll();
            }
        },
        confirmChanges() {
            textEditorerStore.close();
            designEditorRender.recordHistory();
        },
        copyText() {
            designEditorRender.copy();
        },
        deleteText() {
            designEditorRender.del();
        },
        showFontColorPicker() {
            console.log('showFontColor');
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                const color = new Color(activeObject.get("fill"));
                this.currentColor = {
                    r: color.r * 255,
                    g: color.g * 255,
                    b: color.b * 255,
                    a: 1
                };
            }
            this.$refs.colorPicker.open();
            this.colorType = "font_color";
        },
        showStrokeColorPicker() {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                const color = new Color(activeObject.get("stroke"));
                this.currentColor = {
                    r: color.r * 255,
                    g: color.g * 255,
                    b: color.b * 255,
                    a: 1
                };
            }
            this.$refs.colorPicker.open();
            this.colorType = "stroke_color";
        },
        //颜色确认回调
        handleColorConfirm(e) {
            if (this.colorType === 'font_color') {
                designEditorRender.modifyText("fill", e.hex);
            } else if (this.colorType === 'stroke_color') {
                designEditorRender.modifyText("fontFamily", e.hex);
            }
        },

        showStrokeWidthController() {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                this.strokeWidth = activeObject.get("strokeWidth");
                this.isStrokeControllerVisible = true;
            }
        },
        hideStrokeController() {
            this.isStrokeControllerVisible = false;
        },
        handleStrokeWidthChanging(e) {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                const {
                    value
                } = e.detail;
                activeObject.set({
                    strokeWidth: value
                });
                designEditorRender.requestRenderAll();
            }
        },
        handleStrokeWidthChange(e) {
            designEditorRender.recordHistory();
            // 需要记录一下历史记录
        },

        // 显示字符间距控制器
        showCharSpacingController() {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                this.charSpacing = activeObject.get("charSpacing");
                this.isCharSpacingControllerVisible = true;
            }
        },
        hideCharSpacingController() {
            this.isCharSpacingControllerVisible = false;
        },
        handleCharSpacingChanging(e) {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                const {
                    value
                } = e.detail;
                activeObject.set('charSpacing', value);
                designEditorRender.requestRenderAll();
            }
        },
        handleCharSpacingChange(e) {
            designEditorRender.recordHistory();
            // 需要记录一下历史记录
        },

        // 显示行高控制器
        showLineHeightController() {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                this.lineHeight = activeObject.get("lineHeight");
                this.isLineHeightControllerVisible = true;
            }
        },
        hideLineHeightController() {
            this.isLineHeightControllerVisible = false;
        },
        handleLineHeightChanging(e) {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                const {
                    value
                } = e.detail;
                activeObject.set('lineHeight', value);
                designEditorRender.requestRenderAll();
            }
        },
        handleLineHeightChange(e) {
            designEditorRender.recordHistory();
            // 需要记录一下历史记录
        },

        // 显示弯曲控制器
        showBendDegreeController() {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                this.bendDegree = activeObject.get("bendDegree");
                this.isBendDegreeControllerVisible = true;
            }
        },
        hideBendDegreeController() {
            this.isBendDegreeControllerVisible = false;
        },
        handleBendDegreeChanging(e) {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                const {
                    value
                } = e.detail;
                activeObject.set('bendDegree', value);
                designEditorRender.requestRenderAll();
            }

        },
        handleBendDegreeChange(e) {
            designEditorRender.recordHistory();
            // 需要记录一下历史记录 
        },
        showFontFamilySelector() {
            const activeObject = designEditorRender.getActiveObject();
            if (activeObject && ['i-text', "IText", 'text'].includes(activeObject.type)) {
                this.fontFamily = activeObject.get('fontFamily'); // 更新当前字
                designEditorRender.requestRenderAll();
            }
            this.isFontFamilySelectorVisible = true;
        },
        hideFontFamilySelector() {
            this.isFontFamilySelectorVisible = false;
            // 需要记录一下历史记录
        },
        // 字体切换
        async changeFontFamily(fontId) {
            this.fontFamily = fontId; // 更新当前字体
            if (fontId) {
                await fontManage.loadFont([fontId]); // 加载字体
            }
            designEditorRender.modifyText("fontFamily", fontId);
        },
        alignLeft() {
            designEditorRender.modifyText("textAlign", 'left');
        },
        alignCenter() {
            designEditorRender.modifyText("textAlign", 'center');
        },
        alignRight() {
            designEditorRender.modifyText("textAlign", 'right');
        },
    },
    
    computed: {}
};
</script>

<style scoped lang="scss">
.TextEditor {
    position: fixed;
    left: 0;
    width: 100%;
    height: 0px;
    box-sizing: border-box;
    z-index: 999;
    bottom: 0px;

}

.editor-container {
    width: 100%;
    position: absolute;
    bottom: 0;
    padding: 30upx 0;
    padding-top: 0;
    background: #fff;
    transition: all 0.3s;
    transform: translateY(100%);
    padding-bottom: env(safe-area-inset-bottom);
}

.editor-container.active {
    transform: translateY(0%);
}

.editor-header {
    display: flex;
    align-items: center;
    position: relative;
    text-align: right;
    justify-content: space-between;
    width: 100%;
    height: 100upx;
    border-bottom: 1px #eee solid;
    box-shadow: 1px 0 2px rgba(0, 0, 0, 0.1);
    background: #fff;
    padding: 0 20upx;
    box-sizing: border-box;
}

.editor-header textarea {
    flex-grow: 1;
    margin-right: 20upx;
    text-align: left;
    height: 40px;
}

.header-button {
    flex-shrink: 0;
    height: 100rpx;
    font-size: 30rpx;
    color: #666;
    padding: 0px 20rpx;
    box-sizing: border-box;
    white-space: nowrap;
    display: inline-block;
    line-height: 50px;
}

.action-buttons {
    bottom: 0;
    width: 100%;
    height: auto; // 自动适应高度
    background: #ffffff;
    box-shadow: 0px -4px 4px #dfdfdf;
    display: flex;
    flex-wrap: wrap; // 允许换行
    overflow-x: hidden; // 禁止横向滚动
    white-space: normal; // 允许换行
    overflow-y: auto; // 允许上下滚动

    .action-button {
        display: inline-block;
        width: 25%; // 每行显示4个按钮
        height: 48px;
        text-align: center;
        margin: 5px 0;

        .icon {
            display: block;
            margin: 0 auto;
            width: 28px;
            height: 28px;
        }

        .label {
            text-align: center;
            width: 100%;
            display: inline-block;
            font-size: 12px;
        }
    }
}

.font-family-selector {
    position: absolute;
    bottom: 0px;
    width: 100%;
    background-color: #ffffff;
    box-shadow: 0px -4px 4px #dfdfdf;
    padding: 0px;
    box-sizing: border-box;
    padding-bottom: env(safe-area-inset-bottom);
    transition: all 0.3s;
    transform: translateY(100%);
    z-index: 1000;

    &.visible {
        transform: translateY(0%);
    }

    .header {
        position: relative;
        height: 80rpx;
        font-size: 30rpx;
        color: #000000;
        padding: 0px 20rpx;
        box-sizing: border-box;
        white-space: nowrap;
        display: inline-block;
        line-height: 50px;
        text-align: center;
        width: 100%;
        border-bottom: 1px #b4b4b4 solid;

        .close-icon {
            position: absolute;
            top: 10px;
            right: 20px;
            display: inline-block;
            width: 40upx;
            height: 40upx;
        }
    }

    .font-family-list {
        width: 100%;
        max-height: 200px;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;

        .font-family-item {
            position: relative;
            display: inline-block;
            width: calc(50% - 14px);
            margin: 5px;
            height: 50px;
            border: 2px solid #000000;
            border-radius: 4px;

            &.active {
                border: 2px solid #FF5E10;
            }

            .font-preview {
                width: calc(100% - 30px);
                height: 100%;
                margin: 0px 6px 0px 24px;
            }

            .status-icon {
                position: absolute;
                width: 20px;
                height: 20px;
                left: 2px;
                bottom: 2px;
            }

            .status-icon.loadding {
                animation: rotate 1s linear infinite;
            }
        }
    }

}

.char-spacing-controller,
.line-height-controller,
.bend-degree-controller,
.stroke-controller {
    display: flex;
    position: absolute;
    bottom: 0px;
    width: 100%;
    height: calc(60px + env(safe-area-inset-bottom));
    background-color: #ffffff;
    box-shadow: 0px -4px 4px #dfdfdf;
    padding: 20px;
    box-sizing: border-box;
    padding-bottom: env(safe-area-inset-bottom);
    transition: all 0.3s;
    transform: translateY(100%);
    flex-wrap: wrap;
    z-index: 1000;
    /* 允许换行 */

    .warning {
        flex-basis: 100%;
        color: #FF5E10;
        text-align: center;
    }

    &.visible {
        transform: translateY(0%);
    }

    .label {
        display: inline-block;
        width: 80upx;
        vertical-align: middle;
    }

    .slider {
        display: inline-block;
        flex: 1;
        vertical-align: middle;
        margin-top: 2px;
    }

    .close-icon {
        display: inline-block;
        width: 40upx;
        vertical-align: middle;
        height: 20px;
    }
}
</style>